package com.zkingsoft.zkingbase.engine;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.zkingsoft.zkingbase.bean.AppVersion;
import com.zkingsoft.zkingbase.bean.resp.BaseResp;
import com.zkingsoft.zkingbase.bean.resp.MapInfoBean;
import com.zkingsoft.zkingbase.constant.Constant;
import com.zkingsoft.zkingbase.services.UpdateService;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;

/**
 * Created by ytf on 2017/3/3 003.
 * Description: app更新处理类
 */

public class UpdateEngine
{
    private Context mContext;
    private String url, filePath;

    private Retrofit retrofit;
    private Observable<BaseResp> observable;
    private Disposable dis;

    public UpdateEngine(Context context, String url, String filePath)
    {
        this.mContext = context;
        this.url = url;
        this.filePath = filePath;
        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.WEB_BASE)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        observable = retrofit.create(ApiService.class).getUpdateInfo();
    }

    private AppVersion appVersion;

    public void start()
    {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResp>()
                {
                    @Override
                    public void onSubscribe(Disposable d)
                    {
                        dis = d;
                    }

                    @Override
                    public void onNext(BaseResp value)
                    {
                        Log.e("s", value.status);
                        MapInfoBean mi = value.mapInfo;
                        appVersion = mi.appVersion;
                        int currentVersionCode = getVersionCode();
                        if (currentVersionCode < appVersion.getCode())
                        {
                            if(listener != null)
                            {
                                if(listener.onNeedUpdate(appVersion))
                                {
                                    Intent intent = new Intent(mContext, UpdateService.class);
                                    intent.putExtra("download_url", appVersion.getDetails());
                                    intent.putExtra("filepath", filePath);
                                    mContext.startService(intent);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        Log.e("s", e.getMessage());
                        if(dis != null && !dis.isDisposed())
                        {
                            dis.dispose();
                        }
                    }

                    @Override
                    public void onComplete()
                    {
                        if(dis != null && !dis.isDisposed())
                        {
                            dis.dispose();
                        }
                    }
                });

    }

    /**
     * 获取versioncode
     *
     * @return
     */
    public int getVersionCode()
    {
        PackageManager pm = mContext.getPackageManager();
        try
        {
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return 0;
    }
//
//    private void updateNow()
//    {
//        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
//        dialog.setTitle("更新提示");
//        dialog.setIcon(R.mipmap.ic_launcher);
//        String updateInfo = appVersion.getDetails();
//
//        dialog.setMessage(updateInfo);
//        dialog.setPositiveButton("立即体验", new DialogInterface.OnClickListener()
//        {
//
//            @Override
//            public void onClick(DialogInterface dialog, int which)
//            {
//                downloadPackage();
//            }
//        });
//
//        String s = appVersion.getStatus();
//        if (!TextUtils.isEmpty(s) && s.equals("1"))
//        {
//            dialog.setCancelable(false);
//            dialog.setNegativeButton("退出应用", new DialogInterface.OnClickListener()
//            {
//
//                @Override
//                public void onClick(DialogInterface dialog, int which)
//                {
//                    finish();
//                }
//            });
//        } else
//        {
//            dialog.setNegativeButton("下次再说", null);
//        }
//        dialog.show();
//    }

    private UpdateListener listener;
    public void setUpdateListener(UpdateListener l)
    {
        listener = l;
    }

    public interface UpdateListener
    {
        boolean onNeedUpdate(AppVersion ap);
    }

    public interface ApiService
    {
        @GET("app/update_info")
        Observable<BaseResp> getUpdateInfo();
    }
}
